import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as actions from '../actions/index'

class Add extends Component {

    state = {
        name: '',
        city: '',
        id: ''
    }

    componentDidMount() {
        this.setState({
            name: this.props.location.state.item ? this.props.location.state.item.name : '',
            city: this.props.location.state.item ? this.props.location.state.item.city : ''
        })
    }

    changeData(name, value) {
        this.setState({
            [name]: value
        })
    }

    addValue() {
        if (this.state.name && this.state.city) {
            if (!this.props.location.state.flag) {
                let obj = {
                    name: this.state.name,
                    city: this.state.city,
                    id: new Date().getTime()
                }

                this.props.add_Item(obj)
            }
            else {
                let obj = {
                    name: this.state.name,
                    city: this.state.city,
                    id: this.props.location.state ? this.props.location.state.item.id : ''
                }

                this.props.edit_Item(obj)
            }
        }
        this.props.history.go(-1)
    }

    render() {
        let { name, city } = this.state
        return (
            <div>
                <p>姓名：<input value={name} onChange={e => { this.changeData('name', e.target.value) }} /></p>
                <p>地址：<input value={city} onChange={e => { this.changeData('city', e.target.value) }} /></p>
                <button onClick={
                    this.addValue.bind(this)
                }>添加地址</button>
            </div>
        )
    }
}

let mapStateToProps = ({ addReducer }) => {
    return {
        ...addReducer
    }
}

let mapDispatchToProps = (dispatch) => bindActionCreators(actions, dispatch)

export default connect(mapStateToProps, mapDispatchToProps)(Add)